package 反射;

import org.junit.Test;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Demo01 {
    @Test
    public void getFlied() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
        //通过反射获取Person 指定变量对象
        //1.获取Person class对象
        Class<Person> aClass = Person.class;
        Field sex = aClass.getField("sex");
        System.out.println(sex);
        Person person = aClass.newInstance();
        sex.setChar(person,'男');
        System.out.println(person);
    }
    @Test
    public void getMethod() throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        //通过反射获取Person 指定方法对象
        Class<Person> aClass = Person.class;
        Method m = aClass.getMethod("show");//只能获取共有的 并且要指定方法名
        Person person = aClass.newInstance();
        m.invoke(person);
    }
}
//先创建一个实体类
class  Person{
    int id;
    private String name;
    public String sex;

    public Person(int id, String name, String sex) {
        this.id = id;
        this.name = name;
        this.sex = sex;
    }
    private Person(int id, String name) {
        this.id = id;
        this.name = name;
    }
    public Person() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
    public static  void show(){
        System.out.println("aaa");
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}